package com.zhiyou100.springbootweather.job;

import com.zhiyou100.springbootweather.pojo.City;
import com.zhiyou100.springbootweather.service.ICityService;
import com.zhiyou100.springbootweather.util.RedisUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

public class WeatherJob implements Job {
    private static Logger logger = LoggerFactory.getLogger(WeatherJob.class);
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private ICityService cityService;
    @Resource
    private RedisUtils redisUtils;
    //定义获取连接地址,后边只需要加上 名字或id即可
    private static final String url = "http://wthrcdn.etouch.cn/weather_mini?";

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        List<City> cities = cityService.qeuryAll();
        //获取当前时间
        Long start = System.currentTimeMillis();
        for (City city : cities) {
            //查询数据通过网站拉去取
            ResponseEntity<String> forEntity = restTemplate.getForEntity(url + "citykey" + city.getId(), String.class);
            //三元运算符  如果成功 拿到body
            String body = forEntity.getStatusCodeValue()==200?forEntity.getBody():null;
            //存入redis 中
            redisUtils.set(url + "citykey" + city.getId(),body);
        }
        Long end = System.currentTimeMillis();
        logger.info("总耗时间:======"+(end-start)/1000/60);
    }


}
